<template>
    <div class="home">
        <!-- <el-amap vid="amap" :plugin="plugin" class="amap-demo" :center="center"> </el-amap> -->
        <div class="header" ><img :src="headerImage" alt="" srcset=""></div>
        <div class="banner">
            <img :src="banner" alt="" class="bannerimg">
        </div>
        <div class="my_info" @click="toMyPersonalDetails()" v-if="isSignIn">
            <p class="ranking"></p>
            <div class="my_info_con">
                <div class="my_info_l">
                    <p class="img_url">
                        <img :src="myUserInfo.img_path" alt="">
                    </p>
                    <p class="my_info_l_r">
                        <span class="my_info_l_r_t">{{myUserInfo.nickname}}</span>
                        <span class="my_info_l_r_b">{{myUserInfo.index}}</span>
                    </p>
                </div>
                <!-- <div class="my_info_r">
                    <p class="link_num" :class="{yellow:myUserInfo.vote_num>=900}">{{myUserInfo.vote_num}}</p>
                    <p class="pointer">
                        <img v-if="myThumbsUpStatus" src="../../static/img/toupiao48.png"  alt="">
                        <img v-else src="../../static/img/toupiao-1-48.png" @click.stop="toMyThumbsUp()" alt="">
                    </p>
                </div> -->
            </div>
        </div>
        <div class="my_like"  v-show="myNewLikeList.length>0">
            <p class="my_like_title">
                <span>我的关注</span>
            </p>
        </div>
        <ul class="before_three_box" v-show="myNewLikeList.length>0">
            <li v-for="(item,index) in myNewLikeList" :key="index" @click="toMyLikePersonalDetails(item.user_id2)">
                <div class="my_info">
                    <p class="ranking"></p>
                    <div class="my_info_con">
                        <div class="my_info_l">
                            <p class="img_url">
                                <img :src="item.headerImg" alt="">
                            </p>
                            <p class="my_info_l_r">
                                <span class="my_info_l_r_t">{{item.user_nickname}}</span>
                                <!-- <span class="my_info_l_r_b">第{{item.ranking}}名</span> -->
                            </p>
                        </div>
                        <div class="my_info_r">
                            <p class="link_num" :class="{yellow:item.vote_num>=900}">{{item.vote_num}}</p>
                            <p class="pointer">

                                <!-- <img src="../../static/img/toupiao-1-48.png" alt="" @click.stop="addLikeTo(item.id)"> -->
                                <img v-if="item.thumbsUpStatus" src="../../static/img/toupiao48.png" alt="">
                                <img v-else src="../../static/img/toupiao-1-48.png" alt="" @click.stop="addLikeTo(item)">
                            </p>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
        <div class="my_like">
            <p class="my_like_title">
                <span>总排行榜</span>
            </p>
        </div>
        <ul class="before_three_box">
            <li class="before_three_list" v-for="(item,index) in allRankingList" :key="index" @click="toPersonalDetails(item.user_id2)">
                <div class="my_info">
                    <p class="ranking">{{index+1}}</p>
                    <div class="my_info_con">
                        <div class="my_info_l">
                            <p class="img_url">
                                <img :src="item.imgHead" alt="">
                            </p>
                            <p class="my_info_l_r">
                                <span class="my_info_l_r_t">{{item.nickName}}</span>
                            </p>
                        </div>
                        <div class="my_info_r">
                            <p class="link_num" :class="{yellow:item.vote_num>=900}">{{item.vote_num}}</p>
                            <p class="pointer">
<!-- <img src="../../static/img/toupiao-1-48.png" alt="" @click.stop="addLikeTo(item,item.uid)"> -->
                                <img v-if="item.thumbsUpStatus" src="../../static/img/toupiao48.png" alt="">
                                <img v-else src="../../static/img/toupiao-1-48.png" alt="" @click.stop="addLikeTo(item)">
                            </p>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
    </div>
</template>

<script>
import { mapState } from "vuex";
import wx from "weixin-js-sdk";
import { weiXinConfig, weiXinShare } from "../assets/js/wxJsApi";
export default {
  name: "homeSpokesman",
  data() {
    let _self = this;
    return {
      token: localStorage.getItem("token")?localStorage.getItem("token"):'',
      tokenParams:{
          token:localStorage.getItem("token")?localStorage.getItem("token"):''
      },
      headerImage:require('../../static/img/titlebg.png'),
      banner: '',
      defoultBanner:require('../../static/img/banner.jpg'),
      myUserInfo: JSON.parse(localStorage.getItem("myUserInfo")),
      isSignIn: false /*是否登录,是否参与活动 */,
      myImg: "",
      myName: "Fengdi",
      myUid: "1" /*自己的用户id */,
      myRanking: "第三名",
      myThumbsUp: 920 /*我的点赞数量 */,
      myThumbsUpStatus: false /*是否自己已给自己点赞 */,
      thisCity: "上海市" /*当前城市 */,
      myLikeList: [] /*我关注的人数组 */,
      myNewLikeList:[],
      allRankingList: [],
      /*********** */
      positions: {
        lng: "",
        lat: "",
        address: "",
        loaded: false
      },
      center: [121.59996, 31.197646],
    //   plugin: [
    //     {
    //       pName: "Geolocation",
    //       events: {
    //         init(o) {
    //           if(localStorage.getItem("isLocation")){/*登陆之后再定位*/
    //               o.getCurrentPosition((status, result) => {
    //             if (result.position) {
    //               _self.positions.lng = result.position
    //                 .toString()
    //                 .split(",")[0];
    //               _self.positions.lat = result.position
    //                 .toString()
    //                 .split(",")[1];
    //             } else {
    //               _self.positions.lng = _self.center[0];
    //               _self.positions.lat = _self.center[1];
    //             }
    //             if (_self.$route.query.selectCity) {
    //               _self.thisCity = _self.$route.query.selectCity;
    //             } else {
    //               _self.axios
    //                 .get(
    //                   "https://restapi.amap.com/v3/geocode/regeo?key=e9dc8af485ecf2e4a0d41c06691e6325&location=" +
    //                     _self.positions.lng +
    //                     "," +
    //                     _self.positions.lat
    //                 )
    //                 .then(r => {
    //                   if (r.data) {
    //                     let cityAddress = r.data.regeocode.formatted_address;
    //                     let cityAddressIndex = cityAddress.indexOf("市");
    //                     let sortCityAddress = cityAddress.substring(
    //                       0,
    //                       cityAddressIndex + 1
    //                     );
    //                     if (sortCityAddress.indexOf("省") > -1) {
    //                       _self.thisCity = sortCityAddress.split("省")[1];
    //                       _self.$store.commit('setCity',sortCityAddress.split("省")[1])
    //                     } else {
    //                       _self.thisCity = sortCityAddress;
    //                       _self.$store.commit('setCity',sortCityAddress)
    //                     }
    //                   } else {
    //                     this.$p_message(r.data.msg, "error");
    //                   }
    //                 });
    //             }
    //           });
    //           }
              
    //         }
    //       }
    //     }
    //   ]
    };
  },

  created() {
      
    let _self = this;
    if (!localStorage.getItem("token")) {
      this.$p_message("请先登录", "error");
      setTimeout(() => {
        _self.wxSignIn();
      },500);
    } else {
    //   this.token = localStorage.getItem("token").split('"')[1];
      // this.WXConfig.wxShowMenu();
      this.locationCity();
      this.getBanner();
      this.isSign();
      this.getMyInfo();
      this.getVoteList();
      this.wxShare();
    }
  },

  methods: {
      //本地登录调试
    // wxSignIn() {
    //   let THIS_URI = window.location.href
    //   let REDIRECT_URI = "http://xcx.bluecoord.com"
    //   if (!THIS_URI.match(/code/gi)) {
    //     /*没跳转之前 */
    //     window.location.href =
    //       "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    //       this.APPID +
    //       "&response_type=code&scope=snsapi_userinfo&state=123&redirect_uri=" +
    //       REDIRECT_URI +
    //       "#wechat_redirect"; /*hash模式带有#会被微信截取掉,这里将重定向地址放在最后 */
    //   } 
    //   else{
    //      if (THIS_URI.match(/wx\/\?code/)){
    //       /*将code参数放在路由hash后面去，以防参数在hash前面导致页面路径不对 */
    //       let codeUrl = THIS_URI.split("wx/")[1].split("#/")[0];
    //       location.replace(THIS_URI.split("wx/")[0]+'wx/#/'+codeUrl)
    //      }else {
    //       let wxCodeParams = {
    //         code: THIS_URI.split("code=")[1].split("&")[0] //this.$route.query.code
    //       };
    //       this.axios
    //         .post(this.APIHOST + "home/login2", wxCodeParams)
    //         .then(r => {
    //           if (r.data.code === "0") {
    //             this.$store.commit("setToken", r.data.data.token);
    //             this.token= r.data.data.token;
    //             this.tokenParams={
    //                 token:r.data.data.token
    //             },
    //             this.$store.commit("setMyUserInfo", r.data.data);
    //             this.myUserInfo = JSON.parse(
    //               localStorage.getItem("myUserInfo")
    //             );
    //             this.isFromWx();
    //             this.locationCity();
    //             this.getBanner();
    //             this.isSign();
    //             this.getMyInfo();
    //             this.getVoteList();
    //             this.wxShare();
    //           }
    //           if (r.data.code === "1010") {
    //             this.$p_message(r.data.msg);
    //           }
    //         });
    //     }
    //   }
    // },

    //线上登录
    wxSignIn() {
      let REDIRECT_URI =encodeURI(window.location.href) ;
      if (!REDIRECT_URI.match(/code/gi)) {
        /*没跳转之前 */
        localStorage.setItem('isLocation','isLocation');/*用于解决城市定位只定位一次 */
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          this.APPID +
          "&response_type=code&scope=snsapi_userinfo&state=123&redirect_uri=" +
          REDIRECT_URI +
          "#wechat_redirect"; /*hash模式带有#会被微信截取掉,这里将重定向地址放在最后 */
      } 
      else{
        //  if (REDIRECT_URI.match(/wx\/\?code/)){
        //   /*将code参数放在路由hash后面去，以防参数在hash前面导致页面路径不对 */
        //   let codeUrl = REDIRECT_URI.split("wx/")[1].split("#/")[0];
        //   window.location.href=REDIRECT_URI.split("wx/")[0]+'wx/?#/'+codeUrl
        //  }else {
          let wxCodeParams = {
            code: REDIRECT_URI.split("code=")[1].split("&")[0] //this.$route.query.code
          };
          this.axios
            .post(this.APIHOST + "home/login2", wxCodeParams)
            .then(r => {
              if (r.data.code === "0") {
                this.$store.commit("setToken", r.data.data.token);
                this.token= r.data.data.token;
                this.tokenParams={
                    token:r.data.data.token
                },
                this.$store.commit("setMyUserInfo", r.data.data);
                this.myUserInfo = JSON.parse(
                  localStorage.getItem("myUserInfo")
                );
                localStorage.removeItem('isLocation');
                this.isFromWx();
                this.locationCity();
                this.getBanner();
                this.isSign();
                this.getMyInfo();
                this.getVoteList();
                this.wxShare();
              }
              if (r.data.code === "1010") {
                this.$p_message(r.data.msg);
              }
            });
        // }
      }
    },



    /*定位城市 */
    locationCity() {
      if (this.$route.query.selectCity) {
        /*从选择城市页面过来 */
        this.thisCity = this.$route.query.selectCity;
      }
    },
        /*获取banner*/
    getBanner() {

      this.axios
        .get(this.APIHOST + "home/getTopPic?token="+this.token)
        .then(r => {
          if (r.data && r.data.code == '0') {
            if (r.data.data && r.data.data!=='') {
                this.banner=r.data.data
            } else {
              this.banner = this.defoultBanner;
            }
          } else {
              this.banner = this.defoultBanner;
            this.$p_message(r.data.msg, "error");
          }
        });
    },
    /*检测是否登录,是否参与活动 */
    isSign() {
      if (this.myUserInfo) {
        this.isSignIn = true;
        this.getFollowList();
      } else {
        this.isSignIn = false;
      }
    },
    /*获取自己个人信息 */
    getMyInfo() {
        
      this.axios
        .post(this.APIHOST + "user/userinfo" , this.tokenParams)
        .then(r => {});
    },
    toMyThumbsUp(){
        this.$p_message('不能给自己投票', "error");
    },
    /*获取相应城市投票列表 */
    getVoteList() {
      let voteListParams = {
        city: this.thisCity,
        token:this.token
      };
      this.axios
        .post(this.APIHOST + "user/voteList", voteListParams)
        .then(r => {
          if (r.data && r.data.code == 0) {
            if (r.data.data.length > 0) {
              this.allRankingList = r.data.data.map(item => {
                return {
                  imgHead: item.userImage,
                  nickName: item.userName,
                  ranking: item.index,
                  vote_num: item.voteNum,
                  user_id2: item.uid,
                  thumbsUpStatus: false
                };
              });
            } else {
              this.beforeThreeList = [];
              this.allRankingList = [];
            }
          } else {
            this.$p_message(r.data.msg, "error");
          }
        });
    },
        /*关注列表 */
    async getFollowList() {
      await this.axios
        .post(this.APIHOST + "user/followList" , this.tokenParams)
        .then(r => {
          if (r.data && r.data.code == 0) {
            this.myLikeList = r.data.data.filter(item=>{
                return item.add_time===1;
            });
          } else {
            this.$p_message(r.data.msg, "error");
          }
        });

      await this.myLikeList.forEach(item => {
        let userParams = {
          uid: item.user_id2,
          token:this.token
        };
        this.axios
          .post(this.APIHOST + "user/userinfo", userParams)
          .then(r => {
            item["headerImg"] = r.data.data.img_path;
            this.myNewLikeList.push(item)
          });
      });
    },

    /*去我关注的人个人详情页面 */
    toMyLikePersonalDetails(personalId) {
        if (this.$route.query.homeSpokesman) {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            personalId:personalId,
            selectCity: this.thisCity,
            homeSpokesman: "homeSpokesman",
            // isLike:'isLike'
          }
        });
      } else {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            personalId: personalId,
            selectCity: this.thisCity,
            // isLike:'isLike'
          }
        });
      }
    },
    /*去排行榜个人中心 */
    toPersonalDetails(personalId) {
        if (this.$route.query.homeSpokesman) {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            personalId:personalId,
            selectCity: this.thisCity,
            homeSpokesman: "homeSpokesman",
          }
        });
      } else {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            personalId: personalId,
            selectCity: this.thisCity,
          }
        });
      }
    },
    /*去自己个人详情页面 */
    toMyPersonalDetails() {
        if (this.$route.query.homeSpokesman) {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            myPersonalId:this.myUserInfo.user_id,
            selectCity: this.thisCity,
            homeSpokesman: "homeSpokesman"
          }
        });
      } else {
        this.$router.push({
          path: "/wx/personalDetails",
          query: {
            myPersonalId: this.myUserInfo.user_id,
            selectCity: this.thisCity
          }
        });
      }
    },
    /*投票*/
    addLikeTo(val) {
      let voteParams = {
        uid: val.user_id2,
        token:this.token
      };
      this.axios
        .post(this.APIHOST + "user/vote", voteParams)
        .then(r => {
          if (r.data.code == "0") {
              val.thumbsUpStatus = true;
              val.vote_num+=1;
            this.$p_message('投票成功', "success");
          } else {
            this.$p_message(r.data.msg, "error");
          }
        });
    },
    /*微信分享 */
    async wxShare() {
      let _self = this;
      let WxConfig = {};
      let currentUrl =encodeURI(window.location.href.split('#')[0]);
      let wxShareUrl =window.location.href.split('#')[0]+ "?share" + window.location.href.split("#")[1];
      let wxAuthParams = {
        url: currentUrl,
        token:this.token
      };
      await this.axios
        .post(this.APIHOST + "home/wechatJssdk", wxAuthParams)
        .then(r => {
          if (r.data.code === "0") {
            WxConfig = r.data.data;
          }
        });
      await weiXinConfig(WxConfig);
      weiXinShare("",wxShareUrl,"http://xcx.bluecoord.com/wx/static/img/th.png","我为城市代言",_self);
      wx.ready(() => {
                    wx.getLocation({
                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success: function(res) {
                            _self.positions.lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                            _self.positions.lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                            if (_self.$route.query.selectCity) {
                                _self.thisCity = _self.$route.query.selectCity;
                            } else {
                                _self.axios
                                    .get(
                                        "https://restapi.amap.com/v3/geocode/regeo?key=e9dc8af485ecf2e4a0d41c06691e6325&location=" +
                                        _self.positions.lng +
                                        "," +
                                        _self.positions.lat
                                    )
                                    .then(r => {
                                        if (r.data) {
                                            let cityAddress = r.data.regeocode.formatted_address;
                                            let cityAddressIndex = cityAddress.indexOf("市");
                                            let sortCityAddress = cityAddress.substring(
                                                0,
                                                cityAddressIndex + 1
                                            );
                                            if (sortCityAddress.indexOf("省") > -1) {
                                                _self.thisCity = sortCityAddress.split("省")[1];
                                                _self.myCity = sortCityAddress.split("省")[1];
                                                localStorage.setItem('myReCity', sortCityAddress.split("省")[1])
                                                _self.$store.commit('setCity', sortCityAddress.split("省")[1]);
                                                _self.getVoteList();
                                            } else {
                                                _self.thisCity = sortCityAddress;
                                                _self.myCity = sortCityAddress;
                                                localStorage.setItem('myReCity', sortCityAddress);
                                                _self.$store.commit('setCity', sortCityAddress);
                                                _self.getVoteList();
                                            }
                                        } else {
                                            this.$p_message(r.data.msg, "error");
                                        }
                                    });
                            }
                        }
                    });
                })
    }
  },
  beforeRouteEnter(to, from, next) {
      if(document.referrer.match(/weixin/g)){
          next();
      }else{
          next(vm => {
        localStorage.setItem("fromUrl", document.referrer);
    });
      }
  },
  beforeRouteLeave(to, from, next) {
      if(localStorage.getItem('fromUrl')){
          localStorage.removeItem("fromUrl");
      }
    next();
  },
  computed: {
    ...mapState(["thisMyCity"])
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@import url(../assets/less/public.less);
.home {
  @font14();
  background: @config-bg3;

  .amap-demo {
    height: 0;
    overflow: hidden;
  }
  .header{
      width: 100%;
      height: 96px;
      margin-bottom: 10px;
      img{
          width: 100%;
          display: block;
      }
  }
  .banner {
      height: 35vh;
      overflow: hidden;
    width: 100%;
    img {
      width: 100%;
      background: @config-bg5;
      display: block;
      
    }
  }
  .my_info {
    background: @config-bg2;
    height: 120px;
    padding: 0 30px 0 0;
    box-sizing: border-box;
    @flex();
    @justify5();
    .my_info_con {
      flex-grow: 1;
      @flex();
      @justify5();
    }
    .ranking {
      width: 80px;
      height: 120px;
      line-height: 120px;
    }
    .my_info_l {
      @flex();
      @justify1();
      .img_url {
        width: 72px;
        height: 72px;
        border-radius: 72px;
        background: @config-bg3;
        margin-right: 20px;
        overflow: hidden;
        img {
          width: 100%;
        }
      }
      .my_info_l_r {
        span {
          display: block;
          @font14();
          @color2();
          text-align: left;
        }
        .my_info_l_r_b {
          @font11();
          @color5();
        }
      }
    }
    .my_info_r {
      @flex();
      @justify3();
      .link_num {
        margin-right: 48px;
        @font24();
        @color3();
      }
      .yellow {
        @color4();
      }
      .pointer {
        width: 48px;
        img {
          width: 100%;
        }
      }
    }
  }
  .my_like {
    padding: 0 30px;
    .my_like_title {
      height: 100px;
      padding: 46px 0 22px 0;
      box-sizing: border-box;
      text-align: left;
      span {
        margin-top: 46px;
        padding-left: 10px;
        border-left: 4px solid @config-bg4;
        @color5();
      }
    }
  }
  .before_three_box {
    background: @config-bg2;
    li {
      border-bottom: 2px solid @config-bg3;
    }
    li:last-child {
      border-bottom: none;
    }
    .before_three_list {
      @flex();
      @justify5();
      box-sizing: border-box;
      padding: 0 30px 0 0;
      .my_info {
        flex-grow: 1;
        padding: 0;
      }
    }
  }
}
</style>

